package com.softeem.music_sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.music_sys.comm.Result;
import com.softeem.music_sys.entity.Playlist;
import com.softeem.music_sys.entity.PlaylistMusic;
import com.softeem.music_sys.service.PlaylistMusicService;
import com.softeem.music_sys.service.PlaylistService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "歌单接口", description = "歌单相关操作：增删改查等")
@RestController
@RequestMapping("/playlist")
public class PlaylistController {

    @Autowired
    private PlaylistService playlistService;

    @Autowired
    private PlaylistMusicService playlistMusicService;

    // 创建歌单
    @Operation(summary = "创建歌单", description = "创建歌单，提供JSON格式歌单数据")
    @PostMapping
    public Result add(@RequestBody Playlist playlist) {
        // 设置创建时间
        playlist.setCreateTime(new Date());
        boolean flag = playlistService.save(playlist);
        return flag ? Result.success().setMsg("创建成功").setData(playlist) : Result.fail("创建失败");
    }

    // 修改歌单信息
    @Operation(summary = "修改歌单信息", description = "修改歌单信息，提供JSON格式歌单数据")
    @PutMapping
    public Result update(@RequestBody Playlist playlist) {
        boolean flag = playlistService.updateById(playlist);
        return flag ? Result.success().setMsg("修改成功") : Result.fail("修改失败");
    }

    // 删除歌单
    @Operation(summary = "删除歌单", description = "根据歌单ID删除歌单")
    @Parameters({
            @Parameter(name = "id", description = "歌单ID")
    })
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        // 检查歌单是否存在
        Playlist playlist = playlistService.getById(id);
        if (playlist == null) {
            return Result.fail("歌单不存在");
        }
        boolean flag = playlistService.removeById(id);
        // 同时删除歌单中的音乐关联记录
        playlistMusicService.remove(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PlaylistMusic>().eq("playlist_id", id));
        return flag ? Result.success().setMsg("删除成功") : Result.fail("删除失败");
    }

    // 歌单列表查询（分页）
    @Operation(summary = "歌单列表查询", description = "歌单列表查询，支持分页")
    @Parameters({
            @Parameter(name = "page", description = "页码"),
            @Parameter(name = "limit", description = "每页数量")
    })
    @GetMapping("/list")
    public Result list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit
    ) {
        Page<Playlist> pageUtil = new Page<>(page, limit);
        List<Playlist> list = playlistService.list(pageUtil);
        return Result.success().setData(list);
    }

    // 根据ID获取歌单信息
    @Operation(summary = "获取歌单信息", description = "根据歌单ID获取歌单详细信息")
    @Parameters({
            @Parameter(name = "id", description = "歌单ID")
    })
    @GetMapping("/{id}")
    public Result getPlaylistById(@PathVariable Integer id) {
        Playlist playlist = playlistService.getById(id);
        if (playlist == null) {
            return Result.fail("歌单不存在");
        }
        return Result.success().setData(playlist);
    }

    // 根据用户ID查询歌单列表
    @Operation(summary = "根据用户ID查询歌单", description = "根据用户ID查询该用户的所有歌单")
    @Parameters({
            @Parameter(name = "userId", description = "用户ID")
    })
    @GetMapping("/byUser/{userId}")
    public Result getPlaylistByUserId(@PathVariable Integer userId) {
        List<Playlist> list = playlistService.list(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Playlist>().eq("user_id", userId));
        return Result.success().setData(list);
    }

    // 向歌单添加音乐
    @Operation(summary = "向歌单添加音乐", description = "向指定歌单添加音乐")
    @Parameters({
            @Parameter(name = "playlistId", description = "歌单ID"),
            @Parameter(name = "musicId", description = "音乐ID")
    })
    @PostMapping("/addMusic")
    public Result addMusicToPlaylist(
            @RequestParam Integer playlistId,
            @RequestParam Integer musicId
    ) {
        // 检查歌单是否存在
        Playlist playlist = playlistService.getById(playlistId);
        if (playlist == null) {
            return Result.fail("歌单不存在");
        }

        // 检查音乐是否已在此歌单中
        PlaylistMusic existing = playlistMusicService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PlaylistMusic>()
                        .eq("playlist_id", playlistId)
                        .eq("music_id", musicId)
        );
        if (existing != null) {
            return Result.fail("音乐已在歌单中");
        }

        // 添加音乐到歌单
        PlaylistMusic playlistMusic = new PlaylistMusic();
        playlistMusic.setPlaylistId(playlistId);
        playlistMusic.setMusicId(musicId);
        playlistMusic.setAddTime(new Date());
        boolean flag = playlistMusicService.save(playlistMusic);
        return flag ? Result.success().setMsg("添加成功") : Result.fail("添加失败");
    }

    // 从歌单移除音乐
    @Operation(summary = "从歌单移除音乐", description = "从指定歌单移除音乐")
    @Parameters({
            @Parameter(name = "playlistId", description = "歌单ID"),
            @Parameter(name = "musicId", description = "音乐ID")
    })
    @DeleteMapping("/removeMusic")
    public Result removeMusicFromPlaylist(
            @RequestParam Integer playlistId,
            @RequestParam Integer musicId
    ) {
        // 检查歌单是否存在
        Playlist playlist = playlistService.getById(playlistId);
        if (playlist == null) {
            return Result.fail("歌单不存在");
        }

        // 检查音乐是否在歌单中
        PlaylistMusic existing = playlistMusicService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PlaylistMusic>()
                        .eq("playlist_id", playlistId)
                        .eq("music_id", musicId)
        );
        if (existing == null) {
            return Result.fail("音乐不在歌单中");
        }

        // 从歌单移除音乐
        boolean flag = playlistMusicService.remove(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PlaylistMusic>()
                        .eq("playlist_id", playlistId)
                        .eq("music_id", musicId)
        );
        return flag ? Result.success().setMsg("移除成功") : Result.fail("移除失败");
    }

    // 获取歌单中的所有音乐
    @Operation(summary = "获取歌单中的音乐", description = "获取指定歌单中的所有音乐")
    @Parameters({
            @Parameter(name = "playlistId", description = "歌单ID")
    })
    @GetMapping("/musics/{playlistId}")
    public Result getMusicsInPlaylist(@PathVariable Integer playlistId) {
        // 检查歌单是否存在
        Playlist playlist = playlistService.getById(playlistId);
        if (playlist == null) {
            return Result.fail("歌单不存在");
        }

        // 查询歌单中的音乐
        List<PlaylistMusic> list = playlistMusicService.list(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PlaylistMusic>()
                        .eq("playlist_id", playlistId)
        );
        return Result.success().setData(list);
    }
}